package com.tt.qiyuesuo.controller;

import com.tt.qiyuesuo.pojo.FileInfo;
import com.tt.qiyuesuo.service.FileService;
import com.tt.qiyuesuo.utils.Response;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

/**
 * @author tiantao
 * @date 2022/2/22 16:18
 */
@RestController
@Log4j2
public class FileController {

    @Autowired
    FileService fileService;

    @RequestMapping(value = "/upload2")
    public Response<String> upload(@RequestParam("s") String s) throws IOException {
        System.out.println(s);
        return Response.successResponse();
    }

    @RequestMapping(value = "/getFileInfo")
    public Response<FileInfo> getFileInfoByFileName(HttpServletRequest request) {
        String fileName = request.getHeader("fileName");
        if (null == fileName) {
            log.error("FileController getFileInfoByFileName error; fileName:{}",fileName);
            return Response.failedResponse(null);
        }
        FileInfo file = fileService.getFileInfoByFileName(fileName);
        if (null==file){
            log.error("FileController getFileInfoByFileName error 未找到文件");
            return Response.failedResponse(null);
        }
        return Response.successResponse(file);
    }

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
//        System.out.println("ddddddd");
        if (null == file) {
            log.error("FileController upload error; param:{}",file);
            return "file is no exit";
        }
        String filename = file.getOriginalFilename();
        String filetype = filename.substring(filename.lastIndexOf("."));
        String newfile = UUID.randomUUID()+filetype;
        String classespath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        /*生成时间格式*/
        String timeStr= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).replace("-","");
        File newFile = new File(classespath+timeStr+"/"+newfile);
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        try {
            file.transferTo(newFile);
            log.info("文件上传成功，上传路径文件路径：{}",newFile.getPath());

            //保存文件元数据
            fileService.saveFileInfo(filename,newFile);

            return newfile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newfile;
    }


    /**
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "download")
    public Response<String> download(HttpServletRequest request, HttpServletResponse response) throws IOException {

        int BUFFER_SIZE = 4096;
        InputStream in = null;
        OutputStream out = null;

        try{
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            String fileName = request.getHeader("fileName");
            if (null == fileName) {
                log.error("FileController download error; param:{}",fileName);
                return Response.failedResponse("410");
            }
            //根据文件名去得到 path
            String path = fileService.getPathByFileName(fileName);
            if (!StringUtils.hasLength(path)){
                log.error("FileController download error;  文件不存在");
                return Response.failedResponse("文件不存在");
            }

            File file = new File(path);
            response.setContentLength((int) file.length());
            response.setHeader("Accept-Ranges", "bytes");

            int readLength = 0;

            in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
            out = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[BUFFER_SIZE];
            while ((readLength=in.read(buffer)) > 0) {
                byte[] bytes = new byte[readLength];
                System.arraycopy(buffer, 0, bytes, 0, readLength);
                out.write(bytes);
            }

            out.flush();

        }catch(Exception e){
            e.printStackTrace();
            log.error("下载失败");
            return Response.failedResponse();
        }finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return Response.successResponse();
    }

}
